<template>
    <div class="layout-route">
        <div class="card card-search">
            <!-- <div class="flex justify-between align-center">
            <p>
                <span style="color:#fd2f2f;">当前美国时区:(-7)：{{ us_time | parseTime('y-m-d h:i:s 星期a') }}</span>
                <span style="color:#fd2f2f;">,当前欧洲时区:(+2)：{{ eur_time | parseTime('y-m-d h:i:s 星期a') }}</span>
            </p>
        </div> -->

            <div class="calc-warp">
                <div class="mb8" style="font-size: 18px">计算公式</div>
                <div class="mb8">
                    <el-tag effect="plain" type="info">总成本</el-tag><span>=</span><el-tag effect="plain" type="info">预估物流成本</el-tag><span>+</span>
                    <el-tag effect="plain" type="info">预估采购成本</el-tag><span> +</span><el-tag effect="plain" type="info">广告费</el-tag><span>+</span><el-tag>今日退款(预估3个点)</el-tag
                    ><span>+</span><el-tag>平台佣金(预估6个点)</el-tag>
                </div>
                <!-- <div class="mb8">
                    <el-tag effect="plain" type="info">面板销售额</el-tag><span>=</span><el-tag effect="plain" type="info">订单销售额</el-tag><span>+</span>
                    <el-tag effect="plain" type="info">平台折扣</el-tag><span>+</span><el-tag effect="plain" type="info">运费折扣</el-tag><span>-</span><el-tag>Taxes</el-tag>
                </div> -->
                <div>
                    <el-tag effect="plain" type="info">实际盈利</el-tag><span>=</span><el-tag effect="plain" type="info">销售额</el-tag><span>-</span>
                    <el-tag>总成本</el-tag>
                </div>
                <!-- <div style="padding: 20px 0 0 0;">
                    <div class="mb8" style="">今日汇率:1欧元=<span style="font-size: 18px;">{{euroToUsdRate}}</span>美元</div>
                </div> -->
            </div>
            <el-divider></el-divider>
            <el-form :model="queryParams" ref="queryForm" v-show="showSearch" inline label-width="100px">
                <el-form-item label="店铺" prop="shop_id">
                    <el-select v-model="queryParams.shop_id" placeholder="请选择店铺" clearable size="small" style="width: 240px">
                        <el-option v-for="(dict, index) in shopList" :key="index" :label="dict.shop_name" :value="dict.shop_id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="时间" prop="customDate">
                    <el-radio-group v-model="queryParams.customDate" @change="changeCustomDate">
                        <el-radio-button :label="1">今天</el-radio-button>
                        <el-radio-button :label="2">昨天</el-radio-button>
                        <el-radio-button :label="3">近7天</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="日期" prop="date">
                    <el-date-picker v-model="queryParams.date" format="yyyy-MM-dd" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 240px"></el-date-picker>
                </el-form-item>
                <el-form-item label=" ">
                    <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="card">
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="el-icon-download" :loading="download" :disabled="download" @click="handleExport">导出</el-button>
                </el-col>
                <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
            
            <el-table v-loading="loading" :summary-method="getSummaries" show-summary :data="tableData" border script>
                <el-table-column label="店铺" prop="shop_name" min-width="140"></el-table-column>
                <el-table-column label="销售额$" prop="total_price" min-width="120" sortable v-if="!Assistant && !ProductTesting"></el-table-column>
                <el-table-column label="广告费$" prop="advertising" min-width="120" sortable v-if="!isGroup && !ProductTesting">
                    <template slot-scope="scope">
                        <el-link @click="showDailyInfoDialog(scope.row)">{{ scope.row.advertising }}</el-link>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="币种" prop="currency" min-width="120"></el-table-column> -->
                <el-table-column label="单量" prop="quantity" min-width="90" sortable v-if="!Assistant">
                    <template slot-scope="scope">
                        <el-link @click="showDetailDialog(scope.row)">{{ scope.row.quantity }}</el-link>
                    </template>
                </el-table-column>
                <el-table-column label="SKU件数" prop="skuquantity" min-width="120" sortable v-if="!Assistant && !ProductTesting">
                    <template slot-scope="scope">
                        {{ scope.row.skuquantity }}
                    </template>
                </el-table-column>
                <el-table-column label="客单价$" prop="customer_price" min-width="120" sortable v-if="!Assistant && !ProductTesting"></el-table-column>
                <el-table-column label="客单件" prop="customer_sku" min-width="90" sortable v-if="!Assistant && !ProductTesting"></el-table-column>
                <el-table-column label="ROI" prop="roi" min-width="120" sortable v-if="!isGroup && !Assistant && !ProductTesting"></el-table-column>
                <el-table-column label="打包费$" prop="LogisticsMarkupFee" min-width="120" sortable v-if="!isGroup && !Assistant && !ProductTesting"></el-table-column>
                <el-table-column label="预估物流$" prop="estimate_freight" min-width="120" sortable v-if="!isGroup && !Assistant && !ProductTesting"></el-table-column>
                <el-table-column label="采购成本$" prop="material" min-width="120" sortable v-if="!Assistant && !ProductTesting"></el-table-column>
                <el-table-column label="保险费$" prop="premium_price" min-width="120" sortable v-if="!Assistant && !ProductTesting"></el-table-column>
                <el-table-column label="平台佣金$" prop="PlatformCommission" min-width="120" sortable v-if="!isGroup && !Assistant && !ProductTesting"></el-table-column>
                <el-table-column label="预估退款$" prop="refund" min-width="120" sortable v-if="!isGroup && !Assistant && !ProductTesting"></el-table-column>
                <el-table-column label="预估盈利$" prop="profit" min-width="120" sortable  v-if="!isGroup && !Assistant && !ProductTesting"></el-table-column>
                <el-table-column label="运营" prop="admin_name" min-width="120" show-overflow-tooltip v-if="!isGroup && !Assistant && !ProductTesting"></el-table-column>
                <el-table-column label="操作" width="100" fixed="right" v-if="!isGroup && !Assistant && !ProductTesting">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="showDailyDetailDialog(scope.row)" v-show="isAdmin">编辑</el-button>
                        <el-button type="text" style="margin-left: 0;" icon="el-icon-search" @click="showDayDialog(scope.row)" v-if="IntervalDays > 1">每日明细</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="pageInfo.page" :limit.sync="pageInfo.limit" @pagination="getList"></pagination>
        </div>
        <daily-info-dialog v-model="infoDialog.visible" v-if="infoDialog.visible" :params="infoDialog.data" @success="handleQuery"></daily-info-dialog>
        <detail-dialog v-model="detailDialog.visible" v-if="detailDialog.visible" :params="detailDialog.data" @success="handleQuery"></detail-dialog>
        <abnormal-details-dialog v-model="abnormalDialog.visible" v-if="abnormalDialog.visible" :params="abnormalDialog.data"></abnormal-details-dialog>
        <daily-detail-dialog v-model="dailyDetailDialog.visible" v-if="dailyDetailDialog.visible" :params="dailyDetailDialog.data" :type="dailyDetailDialog.type" @success="handleQuery"></daily-detail-dialog>
        
        <DayDetailDialog v-model="DayDialog.visible" v-if="DayDialog.visible" :params="DayDialog.data"></DayDetailDialog>
    </div>
</template>

<script>
import { queryOrderReportDaily, exportOrderReportDaily, getRoleId, getOrderReportDailyRoleId } from '@/api/report'
import { getShopList } from '@/api/shop'

import { exportFile } from '@/utils/index'
import { parseTime } from '@/utils/quickadmin'
import DailyInfoDialog from '../components/DailyInfoDialog'
import DetailDialog from '../components/DetailDialog.vue'
import AbnormalDetailsDialog from '../components/AbnormalDetailsDialog'
import DailyDetailDialog from '../components/DailyDetailDialog.vue'
import DayDetailDialog from '../components/DayDetailDialog.vue'
export default {
    name: 'DailyReportList',
    components: { DailyInfoDialog, DetailDialog, AbnormalDetailsDialog, DailyDetailDialog,DayDetailDialog },
    data() {
        return {
            //时区
            us_time: 0,
            eur_time: 0,

            // 遮罩层
            loading: true,
            download: false,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表格数据
            tableData: [],
            roi: 0,
            customer_price_total: 0,
            customer_sku_total: 0,
            pageInfo: {
                page: 1,
                limit: 10,
            },
            DayDialog: {
                visible: false,
                data: {}
            },
            // 查询参数
            queryParams: {
                shop_id: undefined,
                customDate: 2,
                date: [],
            },
            detailDialog: {
                visible: false,
                data: {},
            },
            infoDialog: {
                visible: false,
                data: {},
            },
            shopList: [],
            abnormalDialog: {
                visible: false,
                data: {},
            },
            advertising_total_status: undefined,
            advertising_total: undefined,
            euroToUsdRate: 0,

            IntervalDays: 1,
            midnightYesterday: 0,
            endOfYesterday: 0,

            dailyDetailDialog: {
                visible: false,
                data: {},
            },
            isGroup: false,
            Assistant: false,
            ProductTesting: false,
            isAdmin: false,
        }
    },
    watch: {
        'queryParams.date': {
            handler(val) {
                if (val?.length == 2) {
                    this.queryParams.customDate = 0
                }
            },
            immediate: true,
            deep: true,
        },
    },
    async created() {
        this.loading = true
        try {
            const result = await getShopList()
            this.shopList = result?.data?.list ?? []
            const groupData = await getOrderReportDailyRoleId()
            console.log(groupData?.data?.group_id)
            this.isAdmin = groupData?.data?.group_id == 1//1	管理员
            this.isGroup = groupData?.data?.group_id == 14//14  供应链
            this.Assistant = groupData?.data?.group_id == 12//12	助理
            this.ProductTesting = groupData?.data?.group_id == 13//13	产品测试
        } catch (error) {
            console.log(error)
            this.loading = false
        }
        this.getList()

        this.now()
    },
    methods: {
        // 北京时间
        now() {
            this.us_time = new Date().getTime() - 15 * 3600 * 1000
            setInterval(() => {
                this.us_time = new Date().getTime() - 15 * 3600 * 1000
            }, 1000)
            this.eur_time = new Date().getTime() - 6 * 3600 * 1000
            setInterval(() => {
                this.eur_time = new Date().getTime() - 6 * 3600 * 1000
            }, 1000)
        },

        changeCustomDate() {
            this.queryParams.date = []
            this.handleQuery()
        },
        showDailyDetailDialog(row) {
            this.dailyDetailDialog.visible = true
            this.dailyDetailDialog.data = row
        },
        showDetailDialog(row) {
            this.detailDialog.visible = true
            this.detailDialog.data = { ...this.queryParams, ...row }
            if (this.detailDialog?.data?.date?.length == 2) {
                this.detailDialog.data.date = [parseTime(this.detailDialog.data.date[0], 'y-m-d'), parseTime(this.detailDialog.data.date[1], 'y-m-d')]
            }
        },
        showDailyInfoDialog(row) {
            this.infoDialog.visible = true
            this.infoDialog.data = { ...this.queryParams, ...row }
            if (this.infoDialog?.data?.date?.length == 2) {
                this.infoDialog.data.date = [parseTime(this.infoDialog.data.date[0], 'y-m-d'), parseTime(this.infoDialog.data.date[1], 'y-m-d')]
            }
        },
        showDayDialog(row) {

            this.DayDialog.visible = true
            this.DayDialog.data.shop_id = row.shop_id

            this.DayDialog.data.IntervalDays = this.IntervalDays
            this.DayDialog.data.midnightYesterday = this.midnightYesterday
            this.DayDialog.data.endOfYesterday = this.endOfYesterday
        },
        handleExport() {
            this.download = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
            }
            if (qyparams.date?.length == 2) {
                qyparams.date = [parseTime(qyparams.date[0], 'y-m-d'), parseTime(qyparams.date[1], 'y-m-d')]
            }
            exportOrderReportDaily(qyparams)
                .then(res => {
                    console.log(res)
                    exportFile(res, () => {
                        this.download = false
                    })
                })
                .catch(err => {
                    console.log(err)
                    this.download = false
                })
        },
        //列表
        getList() {
            this.loading = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
            }
            if (qyparams.date?.length == 2) {
                qyparams.date = [parseTime(qyparams.date[0], 'y-m-d'), parseTime(qyparams.date[1], 'y-m-d')]
            }
            queryOrderReportDaily(qyparams)
                .then(response => {
                    this.tableData = response.data.list || []
                    this.total = response.data.total
                    this.roi = response.data.roi
                    this.customer_price_total = response.data.customer_price_total
                    this.customer_sku_total = response.data.customer_sku_total
                    this.advertising_total_status = response.data.advertising_total_status
                    this.advertising_total = response.data.advertising_total
                    this.euroToUsdRate = response.data.euroToUsdRate
                    this.IntervalDays = response.data.IntervalDays
                    this.midnightYesterday = response.data.midnightYesterday
                    this.endOfYesterday = response.data.endOfYesterday

                    this.$nextTick(() => {
                        this.showSummariesPosition(qyparams)
                    })
                })
                .finally(() => {
                    this.loading = false
                })
        },

        // 搜索按钮操作
        handleQuery() {
            this.pageInfo.page = 1
            this.getList()
        },

        // 重置按钮操作
        resetQuery() {
            this.resetForm('queryForm')

            this.handleQuery()
        },

        // 表尾合计行
        getSummaries(param) {
            const { columns, data } = param
            const sums = []
            
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '统计'
                    return
                }

                const prop = column.property
                if (!prop) {
                    sums[index] = ''
                    return
                }

                // 特殊处理后端返回的合计值
                if (prop === 'roi') {
                    sums[index] = this.roi
                    return
                }
                if (prop === 'customer_price') {
                    sums[index] = this.customer_price_total
                    return
                }
                if (prop === 'customer_sku') {
                    sums[index] = this.customer_sku_total
                    return
                }

                // 直接求和计算
                const total = data.reduce((sum, item) => {
                    const val = Number(item[prop]) || 0
                    return sum + val
                }, 0)
                
                // 根据字段类型显示格式
                if (prop === 'quantity' || prop === 'skuquantity') {
                    sums[index] = Math.round(total).toString()
                } else {
                    sums[index] = total.toFixed(2)
                }
            })
            
            return sums
        },
        showSummariesPosition(row) {
            this.$nextTick(() => {
                try {
                    let table = document.querySelector('.el-table')
                    if (!table) return
                    
                    let tdList = table.querySelectorAll('.el-table_1_column_3')
                    if (!tdList || tdList.length === 0) return

                    const lastCell = tdList[tdList.length - 1]?.querySelector('.cell')
                    if (!lastCell) return

                    if (this.advertising_total_status == 1) {
                        lastCell.innerHTML = "<span class='el-link is-underline'>" + this.advertising_total + '</span>'
                        return true
                    }
                    
                    if (this.advertising_total_status == 2) {
                        lastCell.innerHTML = "<span class='el-link is-underline'>" + this.advertising_total + '</span>'
                        lastCell.onclick = () => {
                            this.showAbnormalDetails(row)
                        }
                    }
                } catch (error) {
                    console.warn('Error in showSummariesPosition:', error)
                }
            })
        },
        showAbnormalDetails(row) {
            this.abnormalDialog.visible = true
            this.abnormalDialog.data = row
        },
    },
}
</script>
<style>
.calc-warp span {
    padding: 0 8px;
}
</style>
